﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace JiveMessenger.ImagePreview.Wikimedia
{
    internal class WikimediaManager
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        internal static WikimediaLink GetWikiMediaLink(Uri url)
        {
            Regex wikimediaRegex = new Regex(@"/(?:wiki/|(?:w/)?index\.php(?:\?title=|/))?(?:%\w\w|[^\d:/&?]){2,50}:([^/&]{1,512}\.(?:jpe?g|gif|png|svgz?)(?!&action=))");
            Match m = wikimediaRegex.Match(url.AbsoluteUri);
            if (!m.Success)
            {
                return null;
            }
            string filename = m.Groups[1].Value;

            WikimediaLink link = new WikimediaLink(filename);
            Uri apiUrl = new Uri(string.Format("http://en.wikipedia.org/w/api.php?action=query&titles=Image:{0}&prop=imageinfo&iiprop=url&format=json&iiurlheight={1}", filename, 1024));
            try
            {
                using (WebClient cli = new WebClient())
                {
                    string response = cli.DownloadString(apiUrl);
                    JObject jo = JObject.Parse(response);
                    JToken thumbUrl = jo.Descendants()
                        .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "thumburl")
                        .Select(p => ((JProperty)p).Value)
                        .FirstOrDefault();

                    JToken originalUrl = jo.Descendants()
                        .Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "url")
                        .Select(p => ((JProperty)p).Value)
                        .FirstOrDefault();
                    //using (var md5 = new MD5CryptoServiceProvider())
                    //{
                    //    var buffer = md5.ComputeHash(Encoding.Default.GetBytes(filename));
                    //    var sb = new StringBuilder();
                    //    for (var i = 0; i < buffer.Length; i++)
                    //    {
                    //        sb.Append(buffer[i].ToString("x2"));
                    //    }

                    //    link.ThumbnailUrl = string.Format("http://upload.wikimedia.org/wikipedia/commons/thumb/{0}/{0}{1}/{2}/{3}px-{2}", sb[0], sb[1], link.Filename, "500");
                    //    link.OriginalImageUrl = string.Format("http://upload.wikimedia.org/wikipedia/commons/{0}/{0}{1}/{2}", sb[0], sb[1], link.Filename);
                    //}
                    link.ThumbnailUrl = thumbUrl.ToString();
                    link.OriginalImageUrl = originalUrl.ToString();
                    return link;
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error in GetWikiMediaLink", ex);
                return null;
            }
        }

    }
}
